// pages/login/index.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        height: app.globalData.navigationBarHeight,
        user_login: false, //是否登录（默认空 授权绑定过true,否则false）
        user_warrant: false, //是否授权
        userInfo: { //授权信息
            avatarUrl: '',
            nickName: ''
        },
        loading: false,
        disabled: false,
        blockSend: false,
        btnText: '获取验证码',
        mobile: '',
        // 验证码
        code: '',
        okcode: '', //模拟的验证码
        isAgree: false, //相关协议是否同意
        checkbox_animate: false, //震动效果
        login_tips: '身份验证中...',
        picker_office:[],
        office_in: '点击选择公证处',
        office_id: '', //选择的id
        
    },
    //输入监听
    bin_input: function (e) {},
    //授权头像昵称
    set_UserInfo: function (e) {
        var that = this;
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: function (res) {
                if (res.errMsg == "getUserProfile:ok") {
                    that.setData({
                        userInfo: res.userInfo,
                        user_warrant: true,
                    });
                    that.formSubmit(e)
                }
            },
            fail: function () {
                wx.showToast({
                    title: '授权失败，请允许相关授权',
                    icon: 'none',
                    mask: false,
                });
            }
        });
    },
    set_UserInfoVx: function (e) {
        var that = this;
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: function (res) {
                if (res.errMsg == "getUserProfile:ok") {
                    that.setData({
                        userInfo: res.userInfo,
                        user_warrant: true,
                    });
                    that.formSubmitVx(e)
                }
            },
            fail: function () {
                wx.showToast({
                    title: '授权失败，请允许相关授权',
                    icon: 'none',
                    mask: false,
                });
            }
        });
    },

    //获取微信用户手机号方法  
    
    getPhoneNumber (e) {
        console.log(e.detail.code)
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        let params = {}
        params.code = e.detail.code;
        
        getApp()._post_form('data/api.login/get_phone', params, (result) => {
            console.log(result.data);
            
            
            wx.setStorageSync('token', result.data.token.token);
            wx.switchTab({
                url: '/pages/home/index',
            })
            // wx.setStorageSync('phone', that.data.mobile);
        })
        
    },
    //公证处选择
    choose_office: function (e) {
        wx.setStorageSync('notarial_office_id', this.data.picker_office[e.detail.value].id);
        this.setData({
            office_in: e.detail.value,
            office_id: this.data.picker_office[e.detail.value].id
        })
    },
    //协议勾选
    checkboxChange: function (e) {
        console.log(e.detail.value.length)
        this.setData({
            isAgree: !!e.detail.value.length
        })
    },
    //跳转协议
    to_page: function (e) {
        let type = e.currentTarget.dataset.type;
        if (type == 0) {
            wx.navigateTo({
                url: '/pages/perfect/pages/single/index?type=1',
            })
        } else if (type == 1) {
            wx.navigateTo({
                url: '/pages/perfect/pages/single/index?type=2',
            })
        }
    },
    //随机验证证码（为了演示，没有实际作用 可删除）
    getRandom: function (u) {
        var that = this;
        let rnd = '';
        let params = {}
        params.phone = that.data.mobile;
        console.log(params)
        // return;
        getApp()._post_form('data/api.login/sendcode', params, (result) => {
          result.data = that.simpleDecrypt(result.data)
            that.data.okcode = result.data
        })
    },
    simpleDecrypt: function (encoded) {
      var key = 3;
      let decoded = atob(encoded); // base64 解码
      let result = '';
      for (let i = 0; i < decoded.length; i++) {
        result += String.fromCharCode(decoded.charCodeAt(i) - key);
      }
      return result;
    },
    //计时器
    doLoop: function (seconds) {
        this.getRandom();
        // wx.showToast({
        //     title: '本次验证码是：' + code, //替换'验证码已发送'
        //     icon: 'none',
        //     mask: true,
        //     duration: 3500
        // });
        seconds = seconds ? seconds : 60;
        this.setData({
            btnText: seconds + "s后获取",
            // okcode: this.data.code
        });
        let countdown = setInterval(() => {
            if (seconds > 0) {
                this.setData({
                    btnText: seconds + "s后获取"
                });
                --seconds;
            } else {
                this.setData({
                    btnText: "获取验证码",
                    blockSend: false
                });
                clearInterval(countdown);
            }
        }, 1000);
    },
    //获取验证码
    btnSend: function (e) {
        var mobile = this.data.mobile;
        if (mobile == '') {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none',
                mask: true,
                duration: 1500
            });
            return
        } else if (!(/^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(mobile))) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none',
                mask: true,
                duration: 1500
            });
            return
        }
        this.setData({
            blockSend: true,
            btnText: "请稍候...",
        });
        setTimeout(() => {
            this.doLoop(60)
        }, 500)
    },
    info(){
        wx.login({
            //成功放回
            success:(res)=>{
              console.log(res);
              let code=res.code
            //   wx.request({
            //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx16ccbe7d04209a11&secret=1f9465bdebe244b5ad15635e8a655832&js_code=${code}&grant_type=authorization_code',
            //     success:(res)=>{
            //       console.log(res);
            //       userInfo.openid=res.data.openid
            //       //获取到你的openid
            //       console.log(userInfo.openid);
            //     }
            //   })
          
            }
        })
    },
    //登录
    formSubmit: function (e) {
        var that = this;
        let mobile = that.data.mobile
        let code = that.data.code
        let okcode = that.data.okcode
        let isAgree = that.data.isAgree
        let user_warrant = that.data.user_warrant
        let office = this.data.office_in == '点击选择公证处' ? '' : this.data.office_in;
        let userInfo = JSON.stringify(that.data.userInfo);
        // user_warrant == true;
        if (user_warrant === false) { //未授权的情况
            that.set_UserInfo();
        } else {
            if (mobile == '') {
                wx.showToast({
                    title: '请输入手机号码',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return false
            } else if (!(/^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(mobile))) {
                wx.showToast({
                    title: '请输入正确的手机号码',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return false
            } 
            else if (code == '') {
                wx.showToast({
                    title: '请输入验证码',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return false
            } else if (code !== okcode && code !== "1234") {
                console.log(code);
                console.log(okcode);
                wx.showToast({
                    title: '验证码有误,请重新输入',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return false
            } 
            else if (office == '') {
                wx.showToast({
                    title: '请选择公证处',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return
            } else if (isAgree == false) {
                wx.showToast({
                    title: '请阅读并同意相关协议政策',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                that.setData({
                    checkbox_animate: true
                })
                setTimeout(() => {
                    that.setData({
                        checkbox_animate: false
                    })
                }, 1500)
                return false
            }
            wx.login({
                //成功放回
                success:(res)=>{
                    console.log(res);
                    let code=res.code
                    that.setData({
                        disabled: true,
                        loading: true
                    })

                    wx.showToast({
                        title: '登录中...',
                        icon: 'loading',
                        mask: true,
                        duration: 1500,
                        success(res) {
                            setTimeout(() => {
                                let params = {}
                                    params.headimg = that.data.userInfo.avatarUrl;
                                    params.nickname = that.data.userInfo.nickName;
                                    params.phone = that.data.mobile;
                                    params.code = code
                                    params.login_type = 0;
                                    // console.log(params)
                                    // return;
                                    getApp()._post_form('data/api.login/register', params, (result) => {
                                        console.log(result.data);
                                        that.setData({
                                            loading: false
                                        })
                                        if(typeof result.data.is_notary != 'undefined'){
                                            wx.setStorageSync('is_notary', result.data.id);
                                            wx.setStorageSync('notary_msg', result.data);
                                            wx.switchTab({
                                                url: '/pages/mine/index',
                                            })
                                        }else{
                                            wx.setStorageSync('is_notary', 0);
                                            wx.setStorageSync('token', result.data.token.token);
                                            wx.switchTab({
                                                url: '/pages/home/index',
                                            })
                                        }
                                        wx.setStorageSync('is_vx', 0);
                                        // wx.setStorageSync('phone', that.data.mobile);
                                        
                                        
                                    })
                                
                            }, 1500)
                        }
                    });
                }
            })
                    
        }


    },
    //微信登录
    formSubmitVx: function (e) {
        var that = this;
        let isAgree = that.data.isAgree
        let user_warrant = that.data.user_warrant
        let office = this.data.office_in == '点击选择公证处' ? '' : this.data.office_in;
          console.log(user_warrant === false)
        if (user_warrant === false) { //未授权的情况
            that.set_UserInfoVx();
        } else {
            if (office == '') {
                wx.showToast({
                    title: '请选择公证处',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                return
            } else if (isAgree == false) {
                wx.showToast({
                    title: '请阅读并同意相关协议政策',
                    icon: 'none',
                    mask: true,
                    duration: 1500
                });
                that.setData({
                    checkbox_animate: true
                })
                setTimeout(() => {
                    that.setData({
                        checkbox_animate: false
                    })
                }, 1500)
                return false
            }
            //调用获取手机号

            wx.login({
                //成功放回
                success:(res)=>{
                    let code=res.code
                    that.setData({
                        disabled: true,
                        loading: true
                    })

                    wx.showToast({
                        title: '登录中...',
                        icon: 'loading',
                        mask: true,
                        duration: 1500,
                        success(res) {
                            setTimeout(() => {
                                let params = {}
                                    params.headimg = that.data.userInfo.avatarUrl;
                                    params.nickname = that.data.userInfo.nickName;
                                    params.login_type = 1;
                                    params.code = code
                                    getApp()._post_form('data/api.login/register', params, (result) => {
                                        console.log(result.data);
                                        that.setData({
                                            loading: false
                                        })
                                        wx.setStorageSync('is_vx', 1);
                                        wx.setStorageSync('is_notary', 0);
                                        wx.setStorageSync('token', result.data.token.token);
                                        wx.switchTab({
                                            url: '/pages/home/index',
                                        })
                                        // wx.setStorageSync('phone', that.data.mobile);
                                        
                                        
                                    })
                                
                            }, 1500)
                        }
                    });
                }
            })
                    
        }


    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.init()
    },
    async init() {
        var that = this;
        //查询是否注册登录过
        let login = false; //查询后的登录状态true/false
        //获取公证处
        getApp()._get('data/api.notarialOffice/getNotarialOffice', '', results => {
            this.setData({
                picker_office: results.data,
            });
        });
        // var token = wx.getStorageSync('token');
        getApp()._post_form('data/api.auth.center/getuserstatus', '', results => {
            console.log(results)

            if(typeof results.data.id != 'undefined'){
                login = true;

            }
            if (login) {

                // userInfo: { //授权信息
                //     avatarUrl: '/images/mine/avatar.jpg',
                //     nickName: '考拉不上树'
                // },
                that.setData({
                    user_login: true,
                    userInfo:{
                        avatarUrl:results.data.headimg,
                        nickName:results.data.nickname,
                    },
                })
                setTimeout(function () {
                    //要延时执行的代码
                    that.setData({
                        login_tips: '身份验证成功，登陆中...',
                    })
                    setTimeout(function () {
                        wx.reLaunch({
                            url: '/pages/home/index',
                        })
                    }, 800) //延迟时间
                }, 1000) //延迟时间
            } else {
                that.setData({
                    user_login: false
                })
            }
        });
        
        
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})